package com.mchsdk.paysdk.bean;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.mchsdk.open.ApiCallback;
import com.mchsdk.open.GPUserResult;
import com.mchsdk.open.MCApiFactory;
import com.mchsdk.paysdk.activity.LoginActivity;
import com.mchsdk.paysdk.activity.TransparencyActivity;
import com.mchsdk.paysdk.bean.thirdlogin.BDThirdLogin;
import com.mchsdk.paysdk.bean.thirdlogin.QQThirdLogin;
import com.mchsdk.paysdk.bean.thirdlogin.WBThirdLogin;
import com.mchsdk.paysdk.bean.thirdlogin.WXThirdLogin;
import com.mchsdk.paysdk.common.Constant;
import com.mchsdk.paysdk.entity.UserLogin;
import com.mchsdk.paysdk.http.thirdlogin.ThirdLoginProcess;
import com.mchsdk.paysdk.entity.ThirdLoginParamsBean;
import com.mchsdk.paysdk.http.thirdloginparams.ThirdLoginParamsProcess;
import com.mchsdk.paysdk.utils.DeviceInfo;
import com.mchsdk.paysdk.utils.MCLog;
import com.mchsdk.paysdk.utils.PreSharedManager;
import com.mchsdk.paysdk.utils.TextUtils;
import com.mchsdk.paysdk.utils.ToastUtil;

/**
 * Created by zhujinzhujin
 * on 2017/1/7.
 */

public class LoginModel {

    private static final String TAG = "LoginModel";


    private static final String LOGINTYPE_WB = "wb";
    private static final String LOGINTYPE_QQ = "qq";
    private static final String LOGINTYPE_WX = "wx";
    private static final String LOGINTYPE_BD = "bd";
    private static final String LOGINTYPE_YK = "yk";

    private Context context;
    private static LoginModel loginModel;
    /**
     * 掉登录控件的等待对话框
     */
    ProgressDialog dialog;


    public static LoginModel instance() {
        if (null == loginModel) {
            loginModel = new LoginModel();
        }
        return loginModel;
    }

    public LoginModel() {
    }


    private Handler mTrirdLoginHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.USER_GET_PARAMS_SUCCESS://获得第三方登录需要的参数
                    ThirdLoginParams(msg.obj);
                    break;
                case Constant.USER_GET_PARAMS_FAIL:
                    dissmissDialog();
                    MCLog.e(TAG, "获得第三方登录参数异常！" + msg.obj);
                    break;
                case Constant.USER_THIRD_PARAMS_SUCCESS://第三方登录成功
                    loginSuccess(true, true, (UserLogin) msg.obj);
                    break;
                case Constant.USER_THIRD_PARAMS_FAIL://第三方登录失败
                    MCLog.e(TAG, "第三方登录失败！" + msg.obj);
                    loginFail();
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 发起游客登录
     */
    public void startVisitorsLogin() {
        ThirdLoginProcess process = new ThirdLoginProcess();
        process.thirdLoginType = ThirdLoginProcess.THIRDLOGIN_YK;
        process.ykAccount = PreSharedManager.getString(Constant.CUSTOMER_YK,
                MCApiFactory.getMCApi().getContext());
        process.post(mTrirdLoginHandle);
    }


    public void requestThirdLoginParams(String thirdLoginType, Context context, ProgressDialog mDialog) {
        this.context = context;
        if (mDialog != null) {
            dialog = mDialog;
        }
        ThirdLoginParamsProcess p = new ThirdLoginParamsProcess();
        MCLog.w(TAG, "thirdLoginType:" + thirdLoginType);
        if (LOGINTYPE_WB.equals(thirdLoginType)) {
            p.login_type = LOGINTYPE_WB;

        } else if (LOGINTYPE_QQ.equals(thirdLoginType)) {
            p.login_type = LOGINTYPE_QQ;
        } else if (LOGINTYPE_WX.equals(thirdLoginType)) {
            p.login_type = LOGINTYPE_WX;
            //判断是否安装微信
            boolean isWxAvaliable = DeviceInfo.isWeixinAvilible(context);
            if (!isWxAvaliable) {
                dissmissDialog();
                ToastUtil.show(context, "没有安装微信");
                return;
            }
        } else if (LOGINTYPE_BD.equals(thirdLoginType)) {
            p.login_type = LOGINTYPE_BD;
        }
        p.post(mTrirdLoginHandle);
    }

    private void ThirdLoginParams(Object obj) {
        ThirdLoginParamsBean bean = (ThirdLoginParamsBean) obj;
        //跳转到控件调用第三方登录SDK
        if (LOGINTYPE_WX.equals(bean.login_type)) {
            if (!TextUtils.isEmpty(bean.weixinappid)) {
                WXThirdLogin.Instance().lunchWXLogin(bean.weixinappid);
                // dialog.dismiss();
            } else {
                loginFail();
                MCLog.e(TAG, "wxappid is null!");
            }
        } else if (LOGINTYPE_QQ.equals(bean.login_type)) {
            if (!TextUtils.isEmpty(bean.qqappid)) {
//                MCLog.w(TAG, "qqappid:" + bean.qqappid);
                QQThirdLogin.Instance().lunchQQLogin(bean.qqappid);
            } else {
                loginFail();
                MCLog.e(TAG, "qqappid is null!");
            }
        } else if (LOGINTYPE_WB.equals(bean.login_type)) {
            if (!TextUtils.isEmpty(bean.weiboappkey)) {
                //dialog.dismiss();
                WBThirdLogin.Instance().lunchWBLogin(
                        bean.weiboappkey, bean.redirecturl, bean.wbscope);
            } else {
                loginFail();
                MCLog.e(TAG, "weiboappkey is null!");
            }
        } else if (LOGINTYPE_BD.equals(bean.login_type)) {
            if (!TextUtils.isEmpty(bean.bdclientid)) {
                MCLog.w(TAG, "bdclientid:" + bean.bdclientid);
                BDThirdLogin.Instance().lunchBDLogin(bean.bdclientid);
            } else {
                loginFail();
                MCLog.e(TAG, "bdclientid is null!");
            }
        } else {
            loginFail();
            MCLog.e(TAG, "第三方登录返回参数错误");
        }
    }

    /**
     * 登录失败
     */
    public void loginFail() {
        GPUserResult userResult = new GPUserResult();
        userResult.setmErrCode(GPUserResult.USER_RESULT_LOGIN_FAIL);
        userResult.setAccountNo("");
        if (ApiCallback.getLoginCallback() != null) {
            ApiCallback.getLoginCallback().onFinish(userResult);
        }
        dissmissDialog();
    }

    /**
     * 登录成功
     *
     * @param isSaveUserInfo 用于是否保存用户信息
     * @param isSavePassword 用于是否保存密码
     * @param loginSuccess   实体类
     */
    public void loginSuccess(boolean isSaveUserInfo, boolean isSavePassword, UserLogin loginSuccess) {
        GPUserResult userResult = new GPUserResult();
        MCLog.w(TAG, "status = " + loginSuccess.getLoginStatus() + " msg = "
                + loginSuccess.getLoginMsg());
        if ("1".equals(loginSuccess.getLoginStatus())) {
            saveUserInfoToPre(isSaveUserInfo, isSavePassword, loginSuccess);
            //先保存在更新
//            String userid = loginSuccess.getAccountUserId();
            userResult.setmErrCode(GPUserResult.USER_RESULT_LOGIN_SUCC);
            userResult.setAccountNo(loginSuccess.getAccountUserId());
            userResult.setAccount(loginSuccess.getUserName());
            userResult.setSign(loginSuccess.getSign());
            userResult.setToken(loginSuccess.getToken());
            if (!loginSuccess.isYKLogin() && !LoginActivity.isAccount) {
                AntiAddictionModel.getInstance().requestAntiAddictionInfo();
            }
//            登录成功后设置个标记
            FlagControl.isLogin = true;
//            MCApiFactory.getMCApi().requestAntiAddiction();
            if (ApiCallback.getLoginCallback() != null) {
                ApiCallback.getLoginCallback().onFinish(userResult);
            }
            TransparencyActivity.instance.closeActivity();
        } else {
            loginFail();
        }
    }


    public void saveRegisterInfoToPre(boolean isSavePassword, String account, String pwd) {
        UserLogin userLogin = new UserLogin();
        userLogin.setUserName(account);
        userLogin.setPassword(pwd);
        userLogin.setAccountUserId("");
        userLogin.setYKLogin(false);
        saveUserInfoToPre(true, isSavePassword, userLogin);
    }

    /**
     * 更新当前用户
     *
     * @param loginSuccess 当前登录用户信息
     */
    public void saveUserInfoToPre(boolean isSaveUserInfo, boolean isSavePassword, final UserLogin loginSuccess) {
        Context context = MCApiFactory.getMCApi().getContext();
        if (null == context) {
            return;
        }
        MCLog.w(TAG, "#saveUserInfoToPre name = " + loginSuccess.getUserName() +
                ", userId = " + loginSuccess.getAccountUserId());
        // 保存用户名和密码
        PersonalCenterModel.getInstance().channelAndGame.setAccount(loginSuccess.getUserName());
        PersonalCenterModel.getInstance().channelAndGame.setPassword(loginSuccess.getPassword());
        PersonalCenterModel.getInstance().channelAndGame.setUserId(loginSuccess.getAccountUserId());
        PersonalCenterModel.getInstance().channelAndGame.setIs_uc(loginSuccess.getIs_uc());

        if (!isSaveUserInfo) {
            return;
        }
        if (loginSuccess.isYKLogin()) {
            PreSharedManager.setString(Constant.CUSTOMER_YK, loginSuccess.getUserName(), context);
        } else {
            PreSharedManager.setString(Constant.CUSTOMER, loginSuccess.getUserName(), context);
            PreSharedManager.setString(Constant.PASSWORD, loginSuccess.getPassword(), context);

            if (isSavePassword) {
                PreSharedManager.setString("savepwd", "1", context);
            } else {
                PreSharedManager.setString("savepwd", "0", context);
            }
        }
    }

    public void dissmissDialog() {
        if (dialog != null) {
            dialog.dismiss();
        }
    }
}
